package com.shenhaofeng.app.widget.banner;

import com.shenhaofeng.app.log.AppLog;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;


/**
 * Created by Administrator on 2016/9/1.
 */
public class BannerScrollTimer {


    private static final String TAG = "BannerScrollTimer";

    private Banner banner;



    public BannerScrollTimer() {
    }


    /**
     * 绑定View
     *
     * @param banner
     */
    public void setup(Banner banner) {
        this.banner = banner;
    }


    /**
     * 失效
     */
    public void invalid() {
        banner = null;
    }


    /**
     * 滚动到下一页
     */
    public void nextPage() {
        if (banner == null) {
            return;
        }
        int count = banner.getCount();
        int nextPage = banner.getCurrentItem()+1;
        nextPage = (nextPage >= count ? 0 : nextPage);
        banner.setCurrentItem(nextPage);
    }


    /**
     * 启动自动滚动
     *
     * @param interval
     * @return
     */
    public Subscription startAutoScroll(final long interval) {
        return Observable.interval(interval, interval, TimeUnit.SECONDS)
                .doOnNext(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        nextPage();
                    }
                })
                .doOnError(new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        AppLog.e(TAG, "橱窗滚动是发生了错误", throwable);
                        startAutoScroll(interval);
                    }
                });
    }
}
